package com.biz.primus.ms.thirdlogin.oauth.service.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.biz.primus.model.thirdlogin.enums.OAuthTypes;
import com.biz.primus.ms.thirdlogin.oauth.api.alipay.AlipayOAuthConfig;
import com.biz.primus.ms.thirdlogin.dao.po.OAuthMember;
import com.biz.primus.ms.thirdlogin.oauth.service.CustomOAuthService;
import lombok.extern.slf4j.Slf4j;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.*;
import org.scribe.oauth.OAuth20ServiceImpl;

/**
 * @author jun.liu
 * @date 2017/10/16
 */
@Slf4j
public class AlipayOAuthService extends OAuth20ServiceImpl implements CustomOAuthService
{

    private final DefaultApi20 api;
    private final AlipayOAuthConfig config;
    private final String authorizationUrl;

    private final String charset = "utf-8";
    private final String mode = "json";
    private final String rsa = "RSA2";

    public AlipayOAuthService(DefaultApi20 api, AlipayOAuthConfig config)
    {
        super(api, config);
        this.api = api;
        this.config = config;
        this.authorizationUrl = getAuthorizationUrl(null);
    }

    @Override
    public Token getAccessToken(Token requestToken, Verifier verifier)
    {
        AlipayClient alipayClient = new DefaultAlipayClient(api.getAccessTokenEndpoint(), config.getApiKey(), config.getApiSecret(), mode, charset, config.getPublicKey(), rsa);
        AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
        request.setBizContent("{" +
                "    \"grant_type\":\"authorization_code\"," +
                "    \"code\":\"" + verifier.getValue() + "\"" +
                "  }");
        try
        {
            AlipayOpenAuthTokenAppResponse response = alipayClient.execute(request);
            return new Token(response.getAppAuthToken(), config.getApiSecret(), response.getBody());
        }
        catch (AlipayApiException e)
        {
            log.error(e.getErrMsg());
        }
        return null;
    }

    @Override
    public OAuthMember getOAuthMember(Token accessToken)
    {
        OAuthMember oAuthMember = new OAuthMember();
        oAuthMember.setOAuthType(getOAuthType());
        Object result = JSON.parse(accessToken.getRawResponse());
        oAuthMember.setOAuthId(JSONPath.eval(result, "$.user_id").toString());
        return oAuthMember;
    }

    @Override
    public OAuthTypes getOAuthType() {
        return OAuthTypes.ALIPAY;
    }

    @Override
    public String getAuthorizationUrl() {
        return authorizationUrl;
    }

}
